package com.amigo.online.provider.search.service.impl;

import java.util.concurrent.TimeUnit;

import com.amigo.online.common.param.result.GlobalConfigInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.amigo.online.common.base.security.LocalUser;
import com.amigo.online.common.core.response.Response;
import com.amigo.online.common.param.result.LocalUserInfo;
import com.amigo.online.common.param.result.UserInfo;
import com.amigo.online.common.util.StringUtils;
import com.amigo.online.provider.search.service.TokenManagerService;
import com.amigo.online.provider.search.service.UserFeignService;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class TokenManagerServiceImpl implements TokenManagerService {

    // private static final Logger logger =
    // LoggerFactory.getLogger(TokenManagerService.class);

    @Autowired
    UserFeignService userFeignService;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean checkToken(String token) {
        if (StringUtils.isBlank(token)) {
            return false;
        }
        // 如果主reids中有token，则不需要去user服务查找
        LocalUserInfo localUser = (LocalUserInfo) redisTemplate.opsForValue().get(token);
        if (localUser != null) {
            redisTemplate.expire(token, 2592000L, TimeUnit.SECONDS);

            LocalUser.setUser(localUser);
            return true;
        }

        ResponseEntity<Response> res = userFeignService.getUserInfoByToken(token);
        if (res.getStatusCodeValue() != 200) {
            return false;
        }
        if (res.getBody() == null) {
            return false;
        }
        if (res.getBody().getMeta().getCode() != 200) {
            return false;
        }
        Object o = res.getBody().getData();
        if (o == null) {
            return false;
        }

        ObjectMapper x = new ObjectMapper();
        x.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        UserInfo user = x.convertValue(o, UserInfo.class);
        LocalUserInfo userinfo = new LocalUserInfo();
        userinfo.setToken(token);
        userinfo.setUser(user);
        LocalUser.setUser(userinfo);
        return true;
    }

}
